package com.walker.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.io.*;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;

@Slf4j
@RestController
public class HelloController {

    @RequestMapping("/getToken")
    public JSONObject getToken(String req) {
        System.out.println(new Date() + req);
        Date now = new Date();

        // 2. 定义目标格式的模板
        // yyyy: 4位年份
        // MM: 2位月份（01-12）
        // dd: 2位日期（01-31）
        // HH: 2位小时（00-23, 24小时制）
        // mm: 2位分钟（00-59）
        // ss: 2位秒钟（00-59）
        // SSS: 3位毫秒（000-999）
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd HH:mm:ss.SSS");

        // 3. 使用format()方法进行格式化
        String formattedDate = sdf.format(now);
        String msg = "{\n" +
                "  \"respHeader\": {\n" +
                "    \"formatVer\": \"01\",\n" +
                "    \"globalSerNo\": \"T204410646U7Q202404021138500000001\",\n" +
                "    \"txnSerNo\": \"0000000000000000\",\n" +
                "    \"parentTxnSerNo\": \"0000000000000000\",\n" +
                "    \"execCode\": \"T204410646U7Q\",\n" +
                "    \"respTime\":  \""+formattedDate+"\",\n" +
                "    \"respStatus\": \"00\",\n" +
                "    \"msgStatus\": \"2\",\n" +
                "    \"zipMethod\": \"00\",\n" +
                "    \"encryptFlag\": \"0\",\n" +
                "    \"encryptKeyVer\": null,\n" +
                "    \"initialVector\": null,\n" +
                "    \"serNo\": \"\",\n" +
                "    \"parentSerNo\": \"\"\n" +
                "  },\n" +
                "  \"respMsgAuth\": null,\n" +
                "  \"respBody\": {\n" +
                "    \"empeRefNo\": \"8584772\",\n" +
                "    \"tokenRefNo\": \"eyJhbGciOiJSUzI1NiJ9.eyJ1c2VyIjoie1widG9rZW5SZWZOb1wiOm51bGwsXCJ0b2tDcnREYXRlXCI6bnVsbCxcInRva1VwZERhdGVcIjpudWxsLFwiY2hubENvZGVcIjpcIjAxXCIsXCJlbXBlUmVmTm9cIjpcIjg1ODQ3NzJcIixcImVtcE5hbWVcIjpudWxsLFwiaW5zdENvZGVcIjpudWxsLFwiaW50ZXJuYWxJbnN0Q29kZVwiOm51bGwsXCJzcGVjaWZpY0pvYkNvZGVcIjpudWxsLFwic3RhbmRhcmRKb2JDb2RlXCI6bnVsbCxcInN1cHJPcmdSZWZub1wiOm51bGwsXCJwbmJybk9yZ1JlZm5vXCI6bnVsbH0iLCJqdGkiOiJPREprT1dObE5ETXROekUwWWkwMFpUY3pMVGxqWXpRdE1UazFNREprWTJZell6ZGkifQ.daWEjo0pTIJc3vdOR5lmqS706XS9Ifzy7fjEnECqEU5uNbAKxDEs6_0B35kBPnBVM44UVf05lQ9H-Pz6_BnOYT7KOncqyn5TKIPbNxBmcPctpBv03HiMAygo-1BQgCb7YCdyWDk9saYb8eQji7OgGnMZg2nvSY64WdSi2Qy-Nqb9js0_MmzH4of9uRaxR3a7urrWVFNd8ZJyOUO4fLlW665wqmlb_8luc36XQu2fApM989-5b4AbVjjiUjIw0JmWlhr5NDIqBgjpRPfTzbh051kI8RdFcM6mWmDhsIOcUvgRx8knO90rg5_2zlIFPHf4X6u67RuGwX-E0q-KIiSJ4Q\",\n" +
                "    \"chnlCode\": \"01\",\n" +
                "    \"tokCrtDate\": \""+formattedDate+"\",\n" +
                "    \"tokUpdDate\":  \""+formattedDate+"\",\n" +
                "  },\n" +
                "  \"respAttach\": null\n" +
                "}";

        return JSON.parseObject(msg);
    }

    @RequestMapping("/checkToken")
    public JSONObject checkToken(@RequestBody String req) {
        System.out.println(req);
        String msg = "{\n" +
                "  \"respBody\": {\n" +
                "    \"P7\": {\n" +
                "      \"empName\": \"舞一\",\n" +
                "      \"instCode\": \"00001\",\n" +
                "      \"internalInstCode\": \"00001\",\n" +
                "      \"pnbrnOrgRefno\": \"00001\",\n" +
                "      \"specificJobCode\": \"0000100001a00b00c00300110121300\",\n" +
                "      \"standardJobCode\": \"a00b00c003001\",\n" +
                "      \"suprOrgRefno\": \"A0001\"\n" +
                "    },\n" +
                "    \"tokenRefNo\": \"eyJhbGciOiJSUzNiJ9.eyJ1c2VyIjoie1widG9rZW5SZWZOb1wiOm51bGwsXCJ0b2tDcnREYXRlXCI6bnVsbCxcInRva1VwZERhdGVcIjpudWxsLFwiY2hubENvZGVcIjpcIjAxXCIsXCJlbXBlUmVmTm9cIjpcIjg1ODQ3NzJcIixcImVtcE5hbWVcIjpudWxsLFwiaW5zdENvZGVcIjpudWxsLFwiaW50ZXJuYWxJbnN0Q29kZVwiOm51bGwsXCJzcGVjaWZpY0pvYkNvZGVcIjpudWxsLFwic3RhbmRhcmRKb2JDb2RlXCI6bnVsbCxcInN1cHJPcmdSZWZub1wiOm51bGwsXCJwbmJybk9yZ1JlZm5vXCI6bnVsbH0iLCJqdGkiOiJPREprT1dObE5ETXROekUwWWkwMFpUY3pMVGxqWXpRdE1UazFNREprWTJZell6ZGkifQ.daWEjo0pTIJc3vdOR5lmqS706XS9Ifzy7fjEnECqEU5uNbAKxDEs6_0B35kBPnBVM44UVf05lQ9H-Pz6_BnOYT7KOncqyn5TKIPbNxBmcPctpBv03HiMAygo-1BQgCb7YCdyWDk9saYb8eQji7OgGnMZg2nvSY64WdSi2Qy-Nqb9js0_MmzH4of9uRaxR3a7urrWVFNd8ZJyOUO4fLlW665wqmlb_8luc36XQu2fApM989-5b4AbVjjiUjIw0JmWlhr5NDIqBgjpRPfTzbh051kI8RdFcM6mWmDhsIOcUvgRx8knO90rg5_2zlIFPHf4X6u67RuGwX-E0q-KIiSJ4Q\",\n" +
                "    \"tokenVerifyCode\": \"00\",\n" +
                "    \"tokenVerifyMsg\": \"验证通过\"\n" +
                "  },\n" +
                "  \"respHeader\": {\n" +
                "    \"encryptFlag\": \"0\",\n" +
                "    \"execCode\": \"T204410MYC58J\",\n" +
                "    \"formatVer\": \"v1\",\n" +
                "    \"globalSerNo\": \"T204410MYC58W202206100758130516913\",\n" +
                "    \"msgStatus\": \"2\",\n" +
                "    \"parentTxnSerNo\": \"0000000000000000\",\n" +
                "    \"respStatus\": \"00\",\n" +
                "    \"respTime\": \"20220610 07:58:13.220\",\n" +
                "    \"txnSerNo\": \"7A19CF176DE2F1CB\",\n" +
                "    \"zipMethod\": \"00\"\n" +
                "  }\n" +
                "}";
//String msg="{\n" +
//        "  \"respHeader\": {\n" +
//        "    \"formatVer\": \"v1\",\n" +
//        "    \"globalSerNo\": \"T204410MYC58W202206100758130516911\",\n" +
//        "    \"txnSerNo\": \"21D654A25F68A055\",\n" +
//        "    \"parentTxnSerNo\": \"0000000000000000\",\n" +
//        "    \"execCode\": \"T204410647O21\",\n" +
//        "    \"respTime\": \"20220829 15:09:30.158\",\n" +
//        "    \"respStatus\": \"01\",\n" +
//        "    \"msgStatus\": \"2\",\n" +
//        "    \"zipMethod\": \"00\",\n" +
//        "    \"encryptFlag\": \"0\",\n" +
//        "    \"encryptKeyVer\": null,\n" +
//        "    \"initialVector\": null,\n" +
//        "    \"serNo\": \"\",\n" +
//        "    \"parentSerNo\": \"\"\n" +
//        "  },\n" +
//        "  \"respMsgAuth\": null,\n" +
//        "  \"respBody\": {\n" +
//        "    \"errCode\": \"SPAPW401\",\n" +
//        "    \"errSysCode\": \"T20441\",\n" +
//        "    \"errDeployUnit\": \"ipP2sess\",\n" +
//        "    \"errSerNo\": \"T204410MYC58W202206100758130516911\",\n" +
//        "    \"errMsg\": \"认证失败,Token不存在!\",\n" +
//        "    \"errAddMsg\": null\n" +
//        "  },\n" +
//        "  \"respAttach\": null\n" +
//        "}";
        return JSON.parseObject(msg);
    }

    @RequestMapping("/checkTokenBT")
    public JSONObject checkTokenBT(@RequestBody String req) {
        System.out.println(req);
//        String msg="{\n" +
//                "  \"respBody\": {\n" +
//                "    \"P7\": {\n" +
//                "      \"empName\": \"舞一\",\n" +
//                "      \"instCode\": \"00001\",\n" +
//                "      \"internalInstCode\": \"00001\",\n" +
//                "      \"pnbrnOrgRefno\": \"00001\",\n" +
//                "      \"specificJobCode\": \"0000100001a00b00c00300110121300\",\n" +
//                "      \"standardJobCode\": \"a00b00c003001\",\n" +
//                "      \"suprOrgRefno\": \"A0001\"\n" +
//                "    },\n" +
//                "    \"tokenRefNo\": \"eyJhbGciOiJSUzNiJ9.eyJ1c2VyIjoie1widG9rZW5SZWZOb1wiOm51bGwsXCJ0b2tDcnREYXRlXCI6bnVsbCxcInRva1VwZERhdGVcIjpudWxsLFwiY2hubENvZGVcIjpcIjAxXCIsXCJlbXBlUmVmTm9cIjpcIjg1ODQ3NzJcIixcImVtcE5hbWVcIjpudWxsLFwiaW5zdENvZGVcIjpudWxsLFwiaW50ZXJuYWxJbnN0Q29kZVwiOm51bGwsXCJzcGVjaWZpY0pvYkNvZGVcIjpudWxsLFwic3RhbmRhcmRKb2JDb2RlXCI6bnVsbCxcInN1cHJPcmdSZWZub1wiOm51bGwsXCJwbmJybk9yZ1JlZm5vXCI6bnVsbH0iLCJqdGkiOiJPREprT1dObE5ETXROekUwWWkwMFpUY3pMVGxqWXpRdE1UazFNREprWTJZell6ZGkifQ.daWEjo0pTIJc3vdOR5lmqS706XS9Ifzy7fjEnECqEU5uNbAKxDEs6_0B35kBPnBVM44UVf05lQ9H-Pz6_BnOYT7KOncqyn5TKIPbNxBmcPctpBv03HiMAygo-1BQgCb7YCdyWDk9saYb8eQji7OgGnMZg2nvSY64WdSi2Qy-Nqb9js0_MmzH4of9uRaxR3a7urrWVFNd8ZJyOUO4fLlW665wqmlb_8luc36XQu2fApM989-5b4AbVjjiUjIw0JmWlhr5NDIqBgjpRPfTzbh051kI8RdFcM6mWmDhsIOcUvgRx8knO90rg5_2zlIFPHf4X6u67RuGwX-E0q-KIiSJ4Q\",\n" +
//                "    \"tokenVerifyCode\": \"00\",\n" +
//                "    \"tokenVerifyMsg\": \"验证通过\"\n" +
//                "  },\n" +
//                "  \"respHeader\": {\n" +
//                "    \"encryptFlag\": \"0\",\n" +
//                "    \"execCode\": \"T204410MYC58J\",\n" +
//                "    \"formatVer\": \"v1\",\n" +
//                "    \"globalSerNo\": \"T204410MYC58W202206100758130516913\",\n" +
//                "    \"msgStatus\": \"2\",\n" +
//                "    \"parentTxnSerNo\": \"0000000000000000\",\n" +
//                "    \"respStatus\": \"00\",\n" +
//                "    \"respTime\": \"20220610 07:58:13.220\",\n" +
//                "    \"txnSerNo\": \"7A19CF176DE2F1CB\",\n" +
//                "    \"zipMethod\": \"00\"\n" +
//                "  }\n" +
//                "}";
        String msg = "{\n" +
                "  \"respHeader\": {\n" +
                "    \"formatVer\": \"v1\",\n" +
                "    \"globalSerNo\": \"T204410MYC58W202206100758130516911\",\n" +
                "    \"txnSerNo\": \"21D654A25F68A055\",\n" +
                "    \"parentTxnSerNo\": \"0000000000000000\",\n" +
                "    \"execCode\": \"T204410647O21\",\n" +
                "    \"respTime\": \"20220829 15:09:30.158\",\n" +
                "    \"respStatus\": \"01\",\n" +
                "    \"msgStatus\": \"2\",\n" +
                "    \"zipMethod\": \"00\",\n" +
                "    \"encryptFlag\": \"0\",\n" +
                "    \"encryptKeyVer\": null,\n" +
                "    \"initialVector\": null,\n" +
                "    \"serNo\": \"\",\n" +
                "    \"parentSerNo\": \"\"\n" +
                "  },\n" +
                "  \"respMsgAuth\": null,\n" +
                "  \"respBody\": {\n" +
                "    \"errCode\": \"SPAPW401\",\n" +
                "    \"errSysCode\": \"T20441\",\n" +
                "    \"errDeployUnit\": \"ipP2sess\",\n" +
                "    \"errSerNo\": \"T204410MYC58W202206100758130516911\",\n" +
                "    \"errMsg\": \"认证失败,Token不存在!\",\n" +
                "    \"errAddMsg\": null\n" +
                "  },\n" +
                "  \"respAttach\": null\n" +
                "}";
        return JSON.parseObject(msg);
    }


    @RequestMapping("/socket")
    public void socket(@RequestBody String req) {

        log.info("掉了socket");
        String serverAddress = "82.204.54.59"; // 服务器地址
        int serverPort = 10088; // 服务器端口

        try (Socket socket = new Socket(serverAddress, serverPort);
             OutputStream out = socket.getOutputStream();
             InputStream in = socket.getInputStream();
             BufferedReader reader = new BufferedReader(new InputStreamReader(in));
             PrintWriter writer = new PrintWriter(out, true)) {

            log.info("服务连接成功");


//            GetTokenVo getTokenVo =new GetTokenVo();
//            getTokenVo.setReqBody(new GReqBody(new GP2("zh_CN","01","ehr号")
//                    ,"随机数"));
//            getTokenVo.setReqHeader(new GReqHeader("parentTxnSerNo","01","globalSerNo","txnSerNo",new Date(),
//                    "P011012A4B3C1","000100","003","T20441P2sess","getToken","v1","27041","09","shardingKey",
//                    "1","1","01","1","0","428A2F9871374491B5C0FBCFE9B5DBA5","serNo","parentSerNo"));
//
//            writer.println(JSON.toJSONString(getTokenVo));

            writer.println(req);
            log.info("Sent to server: " + req);

            // 接收服务器的响应
            String response = reader.readLine();
            log.info("Received from server: " + response);

        } catch (IOException e) {
            log.info("服务连接失败");

            e.printStackTrace();
        }
    }

    @RequestMapping("/http")
    public String http(@RequestBody String req) {

        HttpURLConnection connection = null;
        StringBuilder response = new StringBuilder();

        try {
            // 创建连接
            URL apiUrl = new URL("http://82.204.54.59:10088/test");
            connection = (HttpURLConnection) apiUrl.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("Accept", "application/json");
            connection.setDoOutput(true);

            // 发送请求
            try (OutputStream os = connection.getOutputStream()) {
                byte[] input = req.getBytes(StandardCharsets.UTF_8);
                os.write(input, 0, input.length);
            }

            // 获取响应
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                try (BufferedReader br = new BufferedReader(
                        new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
                    String responseLine;
                    while ((responseLine = br.readLine()) != null) {
                        response.append(responseLine.trim());
                    }
                }
            } else {
                throw new RuntimeException("HTTP POST Request Failed with Error code : " + responseCode);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }

        return response.toString();
    }
}
